extends CharacterBody2D
class_name Player
@onready var animated_sprite_2d = $AnimatedSprite2D

@export var speed = 300.0
@export var run_speed_damping = 0.5 # 滑动阻尼
@export var jump_velocity = -400.0
@export var trample_height = -50
@export var collision_scale:Vector2 = Vector2.ZERO
var FIRE_BALL = preload("res://scenes/fire_ball.tscn")
var body_size:String = "Small"
var direction:int = 1
var is_death:bool = false
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var is_shooting = false
var has_touch_pip = false #碰撞到管道了
var camera:Camera2D = null

func hurt():
	if body_size == "Small":
		die()
	else:
		body_size = "Small"
		change_collision_size()
	pass
	
func die():
	is_death = true
	velocity.y = trample_height * 5
	$CollisionShape2D.set_deferred("disabled",true)
	pass
	
func eat_mushroom():
	body_size = "Big"
	$AnimatedSprite2D.anim_play()
	change_collision_size()
	pass

func eat_flower():
	body_size = "Shooting"
	$AnimatedSprite2D.anim_play()
	change_collision_size()

func shoot():
	var fire_ball = FIRE_BALL.instantiate()
	fire_ball.global_position = $shoot_pos.global_position
	get_tree().root.add_child(fire_ball)
	
func go_into_pip():
	print("player go into pip")
	var under_ground =load("res://scenes/under_ground.tscn")
	get_tree().change_scene_to_packed(under_ground)
	pass
func change_collision_size():
	if body_size == "Small":
		$CollisionShape2D.scale = Vector2(1,1)
	else:
		$CollisionShape2D.scale = collision_scale
	pass

# 踩中敌人后往上弹跳
func trample_enemy():
	velocity.y = trample_height

func _ready() -> void:
	camera = get_tree().get_first_node_in_group("camera")
	
func _physics_process(delta):
	if not is_on_floor():
		velocity.y += gravity * delta
	
	#获取摄像机的最左边，如果玩家想往回走，则不允许 
	var camera_left_bound = camera.global_position.x-camera.get_viewport_rect().size.x/2/camera.zoom.x
	if global_position.x <=camera_left_bound+8 and sign(velocity.x)==-1:
		velocity = Vector2.ZERO
		return
	if global_position.x+8 >= get_tree().root.get_visible_rect().size.x and sign(velocity.x)==1:
		velocity = Vector2.ZERO
		return
		
	direction = int(Input.get_axis("left", "right"))
	
	if direction:
		velocity.x = lerpf(velocity.x,direction * speed,run_speed_damping * delta)
	else:
		velocity.x = move_toward(velocity.x, 0, speed * delta)

	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = jump_velocity
	if Input.is_action_just_released("ui_accept") and velocity.y < 0:
		velocity.y *= 0.5
	if Input.is_action_just_pressed("shoot") and body_size == "Shooting":
		is_shooting = true
		shoot()
	if Input.is_action_just_released("shoot") and body_size == "Shooting":
		is_shooting = false
	if Input.is_action_just_pressed("down"):
		if has_touch_pip:
			go_into_pip()
	move_and_slide()
